﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Collections.Specialized;

namespace ASPMVCUtil.Util
{
    /// <summary>
    /// Clase que hereda RouteValueDictionary y es usada para guardar las llaves y valores del query string. Además puede devolver el query string de la forma
    /// "?llave=valor[&llave=valor]" y clonarse
    /// </summary>
    public class NameValueCollectionRouteValueDictionary : RouteValueDictionary
    {
        /// <summary>
        /// Crea un query string manipulable a parttir del query string de un request
        /// </summary>
        /// <param name="QueryString"></param>
        /// <returns></returns>
        public static NameValueCollectionRouteValueDictionary create(NameValueCollection QueryString)
        {
            var qs = new NameValueCollectionRouteValueDictionary();
            foreach (var key in QueryString.AllKeys)
            {
                qs.Add(key, QueryString[key]);
            }
            return qs;
        }

        /// <summary>
        /// Devuelve el query string de la forma "?llave=valor[&llave=valor]"
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            if (Count > 0)
            {
                var s = "?";
                foreach (var key in Keys)
                {
                    if (this[key] != null)
                    {
                        if (s == "?")
                            s += key + "=" + HttpUtility.UrlEncode(this[key].ToString());
                        else
                            s += "&" + key + "=" + HttpUtility.UrlEncode(this[key].ToString());
                    }
                }
                return s;
            }
            else
                return "";
        }

        /// <summary>
        /// Crea una nueva instancia del objeto con los mismas llaves y valores que el actual
        /// </summary>
        /// <returns></returns>
        public NameValueCollectionRouteValueDictionary Clone()
        {
            var q = new NameValueCollectionRouteValueDictionary();
            foreach (var key in Keys)
            {
                q.Add(key, this[key]);
            }
            return q;
        }
    }
}